package tom.client;

import tom.shared.Company;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.RadioButton;

public class CompanyPopup extends DialogBox {

	public static CompanyPopup popup = GWT.create(CompanyPopup.class);
	private VerticalPanel vPanel;
	private String comCode;

	public String getComCode() {
		return comCode;
	}

	public CompanyPopup() {
		this.setAnimationEnabled(true);
		this.setModal(true);
		this.setText("เลือกบริษัท");

		vPanel = new VerticalPanel();
		vPanel.setSpacing(5);
		this.setWidget(vPanel);
	}

	private Label label;

	public void setLabel(Label label) {
		this.label = label;
	}

	public void updateTitle() {
		Library.getService().getCompany(new AsyncCallback<Company>() {

			@Override
			public void onSuccess(Company result) {
				if (result == null) {
					label.setText("กรุณาเลือกบริษัท");
					comCode = null;
				} else {
					comCode = result.getComCode();
					label.setText(result.getName());
				}
			}

			@Override
			public void onFailure(Throwable caught) {
				Window.alert(caught.getMessage());
			}
		});
	}

	AsyncCallback<Void> setVarCallback = new AsyncCallback<Void>() {
		@Override
		public void onSuccess(Void result) {
			updateTitle();
			MainMenu.menu.refresh();
		}

		@Override
		public void onFailure(Throwable caught) {
			Window.alert(caught.getMessage());
		}
	};

	ClickHandler clickHandler = new ClickHandler() {
		@Override
		public void onClick(ClickEvent event) {
			CompanyPopup.this.hide();
			Library.getService().setSessionVar("comCode",
					((RadioButton) event.getSource()).getTitle(),
					setVarCallback);
			// Window.alert();
		}
	};

	public void open() {
		vPanel.clear();
		Library.getService().getWorkingCompany(new AsyncCallback<String[][]>() {
			@Override
			public void onSuccess(String[][] result) {
				for (int row = 0; row < result.length; row++) {
					RadioButton button = new RadioButton("company",
							result[row][1]);
					button.setStyleName("popup");
					button.setTitle(result[row][0]);
					button.addClickHandler(clickHandler);
					button.setValue(result[row][0].equals(comCode));
					vPanel.add(button);
				}
				CompanyPopup.this.center();
			}

			@Override
			public void onFailure(Throwable caught) {
			}
		});
	}
}
